<template>
  <base-breadcrumb :title="$route.meta.title">
    <a-row :gutter="10" class="page-height">
      <a-col :span="4">
        <a-card class="page-height-tree tree-container">
          <!-- 项目列表 -->
          <PermissionTreeOrganization :showPermission="false" @select="handleSelect" />
        </a-card>
      </a-col>
      <a-col :span="20" class="page-height-list-wrapper">
        <searchData :search-data="searchArr" @search="search" />
        <a-card :bordered="false" class="page-height-list">
          <list-table
            ref="table"
            class="export-table"
            :loading="loading"
            :columns="columns"
            :outSelectedRowKeys.sync="selectedRowKeys"
            :request="loadData"
            :start-index="0"
            :statistics-config="{ use: true, statistics, temp }"
            :export-config="{ use: true }"
            :export-config-text="{ select: '导出选中', all: '导出全部' }"
            :exportPermission="{ select: 'qm_063_aexp_06', all: 'qm_063_sexp_05' }"
            @exportSelect="exportSelect"
            @exportAll="exportAll"
          >
            <template slot="prefix">
              <a-button v-if="hideBuquBtn()" v-btn-permission="'qm_063_app_01'" :disabled="selectOptions.tageCode !== 'PD'" type="primary" icon="plus" @click="handleAdd_Edit(2)">
                申请调拨
              </a-button>
            </template>
            <span slot="serial" slot-scope="text, record, index">{{ index + 1 }}</span>
            <div slot="action" slot-scope="text, record">
              <MoreButton>
                <a v-btn-permission="'qm_063_loo_03'" @click="handleAdd_Edit(0, record)">查看</a>
                <a v-btn-permission="'qm_063_edi_02'" v-if="(record.transferState === '0' || record.transferState === '2') && hideBuquBtn()"  @click="handleAdd_Edit(1, record)">
                  编辑
                </a>
                <a v-btn-permission="'qm_063_del_04'" v-if="record.transferState === '0' && hideBuquBtn()"  @click="handleDelete(record)">
                  删除
                </a>
              </MoreButton>
            </div>
          </list-table>
        </a-card>
      </a-col>
    </a-row>
  </base-breadcrumb>
</template>

<script>
import PermissionTreeOrganization from '@/components/businessComponents/PermissionTreeOrganization'
import { getList, getStatisticsData, deleteItem, exportAll, chooseToExport } from '@/api/quality/meterageEquipmentAllocate'
import BasePage from '@/views/basePage'
import { allocateStatusArr } from '@/views/quality/equipmentManagement/constant/dictionary.js'
import handleDownload from '@/views/quality/equipmentManagement/constant/downloadFile.js'
import moment from 'moment';

export default {
  extends: new BasePage(),
  name: 'a' + Date.now(),
  components: {
    PermissionTreeOrganization
  },

  data() {
    return {
      selectedKeys: [], // 选中节点
      selectOptions: {}, // 选中节点对象
      queryParams: {},
      loading: false,
      columns: [
        {
          title: '序号',
          width: '65px',
          scopedSlots: { customRender: 'serial' }
        },
        {
          title: '设备名称',
          dataIndex: 'mdName'
        },
        {
          title: '申请设备总数',
          dataIndex: 'totalApplyNum'
        },
        {
          title: '落实设备总数',
          dataIndex: 'totalExecuteNum'
        },
        {
          title: '调拨完成时间',
          dataIndex: 'transferCompleteTime',
          customRender: (text) => {
            return text&&moment(text).locale('zh-cn').format('YYYY-MM-DD')
          }
        },
        {
          title: '填报时间',
          dataIndex: 'fillInTime',
        },
        {
          title: '填报人',
          dataIndex: 'fillUserName'
        },
        {
          title: '调拨状态',
          dataIndex: 'transferStateName'
        },
        {
          title: '操作',
          dataIndex: 'action',
          align: 'center',
          scopedSlots: { customRender: 'action' }
        }
      ],
      loadData: parameter => {
        let { pageNo, pageSize } = parameter
        let params = {
          pageNum: pageNo,
          pageSize
        }
        this.loading = true
        const requestParameters = Object.assign({}, params, { param: this.setQueryParam() })
        this.getStatistics(requestParameters)
        return getList(requestParameters)
          .then(res => {
            this.loading = false
            if (res.code === '0') {
              return { code: 200, data: res.data?.list, totalSize: res.data?.total }
            }
          })
          .catch(err => {
            this.loading = false
          })
      },
      searchArr: [
        // 搜索框
        {
          name: '设备名称',
          value: 'mdName',
          type: 'input'
        },
        {
          name: '调拨状态',
          value: 'transferState',
          type: 'select',
          data: allocateStatusArr
        },
        {
          name: '填报时间',
          value: 'fillTime',
          type: 'dateRange'
        },
        {
          name: '填报人',
          value: 'fillUserName',
          type: 'input'
        }
      ],
      selectedRowKeys: [],
      statistics: {},
      temp: () => {
        return (
          <span>
            待提交：<span class="totalNum">{this.statistics.waitCommitNum || 0}个</span>, 调拨处理中：<span class="totalNum">{this.statistics.processingNum || 0}个</span>, 调拨中：
            <span class="totalNum">{this.statistics.transferringNum || 0}个</span>, 调出完成：<span class="totalNum">{this.statistics.transferCompleteNum || 0}个</span>, 被驳回：
            <span class="totalNum">{this.statistics.rejectedNum || 0}个</span>
          </span>
        )
      }
    }
  },
  methods: {
    // 获取统计数据
    getStatistics(params) {
      getStatisticsData(params).then(res => {
        this.statistics = res.data
      })
    },
    exportSelect(data) {
      const transferIdList = data.map(item => item.id)
      let params = this.setQueryParam()
      params.transferIdList = transferIdList
      handleDownload(chooseToExport, {param: params}, '计量设备调拨列表-导出选中')
    },
    exportAll(data) {
      handleDownload(exportAll, {param: this.setQueryParam()}, '计量设备调拨列表-导出全部')
    },
    // 设置查询参数
    setQueryParam() {
      if (this.queryParams.fillTime && this.queryParams.fillTime.length > 0) {
        this.queryParams.fillStartDate = this.queryParams.fillTime[0].format('YYYY-MM-DD')
        this.queryParams.fillEndDate = this.queryParams.fillTime[1].format('YYYY-MM-DD')
        delete this.queryParams.fillTime
      }
      const searchQuery = {}
      if (this.selectOptions.orgId) {
        searchQuery.orgSet = [this.selectOptions.orgId]
        searchQuery.projectSet = this.selectOptions.projectId ? [this.selectOptions.projectId] : []
      } else {
        delete searchQuery.orgSet
        delete searchQuery.projectSet
      }
      this.queryParams.searchQuery = searchQuery
      return  this.queryParams
    },
    handleSelect(node) {
      this.selectOptions = node
      this.search()
    },
    search(values) {
      this.queryParams = values || {}
      this.$refs.table.refresh(true)
    },
    // 新增、编辑、详情（2，1，0）
    handleAdd_Edit(editModel, row) {
      const query = {
        id: row?.id,
        editModel
      }
      if (editModel === 2) {
        query.projectId = this.selectOptions.projectId
      }
      this.$router.push({
        path: '/quality/equipmentManagement/meterageEquipmentAllocateInfo',
        query
      })
    },
    // 删除
    async handleDelete(row) {
      let res = await deleteItem({ id: row.id })
      if (res.data) {
        this.$refs.table.refresh(true)
      }
    }
  }
}
</script>
